package com.ssm.controller;

import com.ssm.common.Result;
import com.ssm.common.ResultGenerator;
import com.ssm.entity.Article;
import com.ssm.entity.PageBean;
import com.ssm.service.ArticleService;
import com.ssm.utils.DateUtil;
import com.ssm.utils.ResponseUtil;
import com.ssm.utils.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LinYaTing on 2018/12/9 23:37
 */
@Controller
@RequestMapping(value = "/articles")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    private static final long serialVersionUID = 1L;

    private static final Logger log = Logger.getLogger(ArticleController.class);// 日志文件

    @RequestMapping(value = "/datagrid", method = RequestMethod.POST)
    public String list(@RequestParam(value = "page", required = false) String page,
                       @RequestParam(value = "rows", required = false) String rows,
                       Article article, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (page !=null && rows !=null) {
            PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
            map.put("start", pageBean.getStart());
            map.put("size", pageBean.getPageSize());
        }
        if (article !=null) {
            map.put("articleTitle", StringUtil.formatLike(article.getArticleTitle()));
        }
        List<Article> articleList = articleService.findArticle(map);
        Long total = articleService.getTotalArticle(map);
        JSONObject result = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(articleList);
        result.put("rows", jsonArray);
        result.put("total", total);
        log.info("request: article/list, map:" + map.toString());
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public Result add(@RequestBody Article article) throws Exception{
        int resultTotal = 0;
        article.setArticleCreateDate(DateUtil.getCurrentDateStr());
        resultTotal = articleService.addArticle(article);
        log.info("request:article/add, " + article.toString());
        if (resultTotal > 0) {
            return ResultGenerator.getSuccessResult();
        }else {
            return ResultGenerator.getFailResult("添加失败了");
        }
    }
}
